import 'package:FlutterStudy/BaseWidgget.dart';
import 'package:FlutterStudy/utils/splash.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(SliverDemoApp());
}

class SliverDemoApp extends StatelessWidget  with Splash{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Sliver Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: SliverMainPage(),
    );
  }
}

class SliverDemoHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    hideScreen();
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 1. SliverAppBar - 可折叠的AppBar
          SliverAppBar(
            expandedHeight: 200.0,
            floating: false,
            pinned: true,
            snap: false,
            flexibleSpace: FlexibleSpaceBar(
              title: Text('Sliver Demo'),
              background: Image.network(
                'https://picsum.photos/400/200',
                fit: BoxFit.cover,
              ),
            ),
            actions: [
              IconButton(
                icon: Icon(Icons.search),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.more_vert),
                onPressed: () {},
              ),
            ],
          ),

          // 2. SliverToBoxAdapter - 包装普通Widget
          SliverToBoxAdapter(
            child: Container(
              padding: EdgeInsets.all(16.0),
              color: Colors.grey[200],
              child: Text(
                '这是 SliverToBoxAdapter 示例，用于包装普通的 Box Widget',
                style: TextStyle(fontSize: 16),
              ),
            ),
          ),

          // 3. SliverList - 列表
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return ListTile(
                  leading: CircleAvatar(
                    child: Text('${index + 1}'),
                  ),
                  title: Text('列表项 ${index + 1}'),
                  subtitle: Text('这是列表项的副标题'),
                  trailing: Icon(Icons.arrow_forward_ios),
                );
              },
              childCount: 5,
            ),
          ),

          // 4. SliverPadding - 添加内边距
          SliverPadding(
            padding: EdgeInsets.all(16.0),
            sliver: SliverToBoxAdapter(
              child: Container(
                height: 100,
                color: Colors.orange,
                child: Center(
                  child: Text(
                    '带内边距的 Sliver',
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                ),
              ),
            ),
          ),

          // 5. SliverGrid - 网格布局
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: 150.0,
              mainAxisSpacing: 10.0,
              crossAxisSpacing: 10.0,
              childAspectRatio: 1.0,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Container(
                  decoration: BoxDecoration(
                    color: Colors.primaries[index % Colors.primaries.length],
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  child: Center(
                    child: Text(
                      'Grid $index',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                );
              },
              childCount: 12,
            ),
          ),

          // 6. SliverFixedExtentList - 固定高度列表
          SliverFixedExtentList(
            itemExtent: 80.0,
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Card(
                  margin: EdgeInsets.all(8.0),
                  child: Center(
                    child: Text(
                      '固定高度列表项 $index',
                      style: TextStyle(fontSize: 18),
                    ),
                  ),
                );
              },
              childCount: 5,
            ),
          ),

          // 7. SliverPrototypeExtentList - 基于原型的列表
          SliverPrototypeExtentList(
            prototypeItem: Container(
              height: 70.0,
              color: Colors.transparent,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Container(
                  margin: EdgeInsets.all(8.0),
                  decoration: BoxDecoration(
                    color: Colors.purple[100 * (index % 9 + 1)],
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  child: ListTile(
                    title: Text('原型列表项 $index'),
                    subtitle: Text('基于原型高度的列表项'),
                  ),
                );
              },
              childCount: 5,
            ),
          ),

          // 8. SliverPersistentHeader - 持久头部
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverPersistentHeaderDelegate(
              minHeight: 60.0,
              maxHeight: 100.0,
              child: Container(
                color: Colors.green,
                child: Center(
                  child: Text(
                    '持久头部 - 始终可见',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ),
          ),

          // 9. SliverList with ExpansionTile
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Card(
                  margin: EdgeInsets.all(8.0),
                  child: ExpansionTile(
                    title: Text('可展开项 $index'),
                    children: [
                      ListTile(
                        title: Text('子项 1'),
                      ),
                      ListTile(
                        title: Text('子项 2'),
                      ),
                      ListTile(
                        title: Text('子项 3'),
                      ),
                    ],
                  ),
                );
              },
              childCount: 3,
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                return Card(
                  margin: EdgeInsets.all(8.0),
                  child: ExpansionTile(
                    title: Text('可展开项 $index'),
                    children: [
                      ListTile(
                        title: Text('子项 1'),
                      ),
                      ListTile(
                        title: Text('子项 2'),
                      ),
                      ListTile(
                        title: Text('子项 3'),
                      ),
                    ],
                  ),
                );
              },
              childCount: 3,
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                return Card(
                  margin: EdgeInsets.all(8.0),
                  child: ExpansionTile(
                    title: Text('可展开项 $index'),
                    children: [
                      ListTile(
                        title: Text('子项 1'),
                      ),
                      ListTile(
                        title: Text('子项 2'),
                      ),
                      ListTile(
                        title: Text('子项 3'),
                      ),
                    ],
                  ),
                );
              },
              childCount: 3,
            ),
          ),
          // 10. SliverFillRemaining - 填充剩余空间
          SliverFillRemaining(
            hasScrollBody: false,
            child: Container(
              color: Colors.blue[100],
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.check_circle,
                      size: 60,
                      color: Colors.green,
                    ),
                    SizedBox(height: 20),
                    Text(
                      '已到达底部',
                      style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                    ),
                    SizedBox(height: 10),
                    Text(
                      '这是 SliverFillRemaining，填充剩余空间',
                      style: TextStyle(fontSize: 16, color: Colors.grey[600]),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// 自定义 SliverPersistentHeaderDelegate
class _SliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double minHeight;
  final double maxHeight;
  final Widget child;

  _SliverPersistentHeaderDelegate({
    required this.minHeight,
    required this.maxHeight,
    required this.child,
  });

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => maxHeight;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverPersistentHeaderDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
           minHeight != oldDelegate.minHeight ||
           child != oldDelegate.child;
  }
}

// 高级 Sliver 示例页面
class AdvancedSliverDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('高级 Sliver 示例'),
      ),
      body: CustomScrollView(
        slivers: [
          // 可折叠的搜索栏
          SliverAppBar(
            pinned: true,
            floating: true,
            snap: true,
            title: Text('可折叠搜索栏'),
            bottom: PreferredSize(
              preferredSize: Size.fromHeight(60.0),
              child: Padding(
                padding: EdgeInsets.all(8.0),
                child: TextField(
                  decoration: InputDecoration(
                    hintText: '搜索...',
                    prefixIcon: Icon(Icons.search),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(30.0),
                    ),
                  ),
                ),
              ),
            ),
          ),

          // 分类标题
          SliverPersistentHeader(
            pinned: true,
            delegate: _SectionHeaderDelegate(
              title: '热门推荐',
            ),
          ),

          // 横向滚动列表
          SliverToBoxAdapter(
            child: Container(
              height: 150,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: 10,
                itemBuilder: (context, index) {
                  return Container(
                    width: 120,
                    margin: EdgeInsets.all(8.0),
                    decoration: BoxDecoration(
                      color: Colors.pink[100 * (index % 9 + 1)],
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                    child: Center(
                      child: Text(
                        '推荐 $index',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  );
                },
              ),
            ),
          ),

          // 分类标题
          SliverPersistentHeader(
            pinned: true,
            delegate: _SectionHeaderDelegate(
              title: '产品列表',
            ),
          ),

          // 产品网格
          SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 10.0,
              mainAxisSpacing: 10.0,
              childAspectRatio: 0.75,
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return Card(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: Image.network(
                          'https://picsum.photos/200/200?random=$index',
                          width: double.infinity,
                          fit: BoxFit.cover,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '产品 $index',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                            SizedBox(height: 4),
                            Text(
                              '\$${(index + 1) * 10}',
                              style: TextStyle(
                                color: Colors.red,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                );
              },
              childCount: 20,
            ),
          ),
        ],
      ),
    );
  }
}

// 分类标题代理
class _SectionHeaderDelegate extends SliverPersistentHeaderDelegate {
  final String title;

  _SectionHeaderDelegate({required this.title});

  @override
  double get minExtent => 50.0;

  @override
  double get maxExtent => 50.0;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.blue,
      padding: EdgeInsets.symmetric(horizontal: 16.0),
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          Spacer(),
          Text(
            '查看更多',
            style: TextStyle(color: Colors.white70),
          ),
          Icon(
            Icons.arrow_forward_ios,
            size: 16,
            color: Colors.white70,
          ),
        ],
      ),
    );
  }

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}

// 主页面，包含导航到不同 Sliver 示例
class SliverMainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sliver 示例集合'),
      ),
      body: ListView(
        padding: EdgeInsets.all(16.0),
        children: [
          _buildDemoCard(
            context,
            title: '基础 Sliver 示例',
            subtitle: '包含各种基础 Sliver 组件',
            onTap: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SliverDemoHome()),
            ),
          ),
          _buildDemoCard(
            context,
            title: '高级 Sliver 示例',
            subtitle: '包含更复杂的 Sliver 布局',
            onTap: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AdvancedSliverDemo()),
            ),
          ),
          _buildDemoCard(
            context,
            title: '自定义 Sliver 示例',
            subtitle: '展示自定义 Sliver 的实现',
            onTap: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => CustomSliverDemo()),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDemoCard(
    BuildContext context, {
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return Card(
      margin: EdgeInsets.only(bottom: 16.0),
      child: ListTile(
        title: Text(title),
        subtitle: Text(subtitle),
        trailing: Icon(Icons.arrow_forward_ios),
        onTap: onTap,
      ),
    );
  }
}

// 自定义 Sliver 示例
class CustomSliverDemo extends StatefulWidget {
  @override
  _CustomSliverDemoState createState() => _CustomSliverDemoState();
}

class _CustomSliverDemoState extends State<CustomSliverDemo> {
  bool _showHeader = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            title: Text('自定义 Sliver'),
            pinned: true,
            actions: [
              IconButton(
                icon: Icon(_showHeader ? Icons.visibility : Icons.visibility_off),
                onPressed: () {
                  setState(() {
                    _showHeader = !_showHeader;
                  });
                },
              ),
            ],
          ),

          // 条件显示的 Sliver
          if (_showHeader)
            SliverToBoxAdapter(
              child: Container(
                height: 100,
                color: Colors.amber,
                child: Center(
                  child: Text(
                    '条件显示的 Header',
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ),

          // 自定义 SliverPersistentHeader
          SliverPersistentHeader(
            delegate: _CustomHeaderDelegate(),
            pinned: true,
          ),

          // 普通列表
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return ListTile(
                  title: Text('列表项 $index'),
                  subtitle: Text('这是第 $index 个列表项'),
                  leading: CircleAvatar(
                    backgroundColor: Colors.blue,
                    child: Text('${index + 1}'),
                  ),
                );
              },
              childCount: 50,
            ),
          ),
        ],
      ),
    );
  }
}

// 自定义 Header Delegate
class _CustomHeaderDelegate extends SliverPersistentHeaderDelegate {
  @override
  double get minExtent => 60.0;

  @override
  double get maxExtent => 120.0;

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    final progress = shrinkOffset / (maxExtent - minExtent);
    final opacity = 1.0 - progress.clamp(0.0, 1.0);

    return Container(
      color: Colors.deepPurple,
      child: Stack(
        children: [
          Center(
            child: Opacity(
              opacity: opacity,
              child: Text(
                '自定义 Header',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 24 - (progress * 8),
                ),
              ),
            ),
          ),
          if (progress > 0.5)
            Positioned(
              bottom: 10,
              left: 0,
              right: 0,
              child: LinearProgressIndicator(
                value: progress,
                backgroundColor: Colors.white30,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ),
        ],
      ),
    );
  }

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) => true;
}
